package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.ICategoryService;
import com.itheima.reggie.service.IDishService;
import com.itheima.reggie.service.ISetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 菜品套餐业务层实现
 *
 * @author panda
 * @since 2022/12/31 1:55
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements ICategoryService {
    @Autowired
    private IDishService dishService;

    @Autowired
    private ISetmealService setmealService;

    @Autowired
    private ICategoryService categoryService;

    @Override
    public void removeCategoryById(String id) {
        LambdaQueryWrapper<Dish> dishQueryWrapper = new LambdaQueryWrapper<>();
        dishQueryWrapper.eq(Dish::getCategoryId, id);
        //进行判断,
        //根据当前分类的ID，查询该分类下是否存在菜品,则不能进行删除
        int countDish = dishService.count(dishQueryWrapper);
        //如果大于0,则需要抛出异常
        if (countDish > 0) {
            //需要自定义一个异常,专门用来处理category的分类异常
            throw new CustomException("当前分类下关联了菜品，不能删除");
        }
        //根据当前分类的ID，查询该分类下是否存在套餐,则不能进行删除
        LambdaQueryWrapper<Setmeal> setmealQueryWrapper = new LambdaQueryWrapper<>();
        setmealQueryWrapper.eq(Setmeal::getCategoryId, id);
        //进行判断,
        //根据当前分类的ID，查询该分类下是否存在菜品,则不能进行删除
        int countSetmeal = setmealService.count(setmealQueryWrapper);
        //如果大于0,则需要抛出异常
        if (countSetmeal > 0) {
            //需要自定义一个异常,专门用来处理category的分类异常
            throw new CustomException("当前分类下关联了套餐，不能删除");
        }
        //上面都没有抛出异常时,说明可以删除
        categoryService.removeById(id);
    }
}